const path = require('path');
const moment = require('moment');
const { response } = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const db = require('../config/db');

// 头像上传
exports.uploadAvatar = (req, res) => {
  if (!req.file) {
    return res.status(400).json({ success: false, message: '未上传文件' });
  }
  // 返回图片URL（前端可直接用）
  const url = `/uploads/avatars/${req.file.filename}`;
  // 也可以返回完整url，方便前端调试
  // const fullUrl = req.protocol + '://' + req.get('host') + url;
  res.json({ success: true, url });
};

// 修改基础信息
exports.updateProfile = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { username, email, phone, avatar } = req.body;
    // 只允许修改部分字段
    await db.query(
      'UPDATE users SET username=?, email=?, phone=?, avatar_url=?, updated_at=? WHERE user_id=?',
      [username, email, phone, avatar, moment().format('YYYY-MM-DD HH:mm:ss'), userId]
    );
    res.json({ success: true, message: '信息已更新' });
  } catch (error) {
    res.status(500).json({ success: false, message: '更新失败' });
  }
};

// 我的收藏
exports.favorites = async (req, res) => {
  try {
    const userId = req.user.user_id;
    // 关联 favorites 和 products 表，查出收藏商品
    const [rows] = await db.query(
      `SELECT f.favorite_id, f.product_id, p.title, p.price, p.avatar_url, p.status
       FROM favorites f
       JOIN products p ON f.product_id = p.product_id
       WHERE f.user_id = ?
       ORDER BY f.created_at DESC`,
      [userId]
    );
    res.json({ favorites: rows });
  } catch (error) {
    res.status(500).json({ favorites: [] });
  }
};

// 浏览历史（旧版，不支持筛选排序）
exports.history = async (req, res) => {
  try {
    const userId = req.user.user_id;
    // 关联 browse_history 和 products 表，查出浏览商品
    const [rows] = await db.query(
      `SELECT h.history_id, h.product_id, h.view_time, p.title, p.price, p.avatar_url, p.status
       FROM browse_history h
       JOIN products p ON h.product_id = p.product_id
       WHERE h.user_id = ?
       ORDER BY h.view_time DESC`,
      [userId]
    );
    res.json({ history: rows });
  } catch (error) {
    res.status(500).json({ history: [] });
  }
};

// 添加浏览历史
exports.addBrowseHistory = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { product_id } = req.body;

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [浏览历史] 用户 ${userId} 记录浏览商品 ${product_id}`);

    // 检查商品是否存在
    const [products] = await db.query('SELECT product_id FROM products WHERE product_id = ?', [product_id]);
    if (products.length === 0) {
      return res.status(404).json({ success: false, message: '商品不存在' });
    }

    // 先检查是否已存在该商品的浏览记录（可选择更新时间或跳过）
    const [existingHistory] = await db.query(
      'SELECT history_id FROM browse_history WHERE user_id = ? AND product_id = ?',
      [userId, product_id]
    );

    if (existingHistory.length > 0) {
      // 更新现有记录的时间
      await db.query(
        'UPDATE browse_history SET view_time = ? WHERE history_id = ?',
        [moment().format('YYYY-MM-DD HH:mm:ss'), existingHistory[0].history_id]
      );
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [浏览历史] 更新商品 ${product_id} 的浏览时间`);
    } else {
      // 添加新记录
      await db.query(
        'INSERT INTO browse_history (user_id, product_id, view_time) VALUES (?, ?, ?)',
        [userId, product_id, moment().format('YYYY-MM-DD HH:mm:ss')]
      );
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [浏览历史] 添加商品 ${product_id} 的浏览记录成功`);
    }

    res.json({ success: true, message: '记录浏览历史成功' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [浏览历史] 记录失败: ${error.message}`);
    res.status(500).json({ success: false, message: '记录浏览历史失败' });
  }
};

// 浏览历史（新版，支持筛选排序和分页）
exports.getBrowseHistory = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { page = 1, page_size = 10, sort_by = 'view_time_desc', category_ids, min_price, max_price, time_range, keyword } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(page_size, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [浏览历史] 用户 ${userId} 请求浏览历史: 页码=${currentPage}, 每页数量=${itemsPerPage}, 排序=${sort_by}${keyword ? `, 关键词=${keyword}` : ''}`);

    // 构建SQL查询
    let sql = `
      SELECT h.history_id, h.product_id, h.view_time, p.title, p.price, p.original_price, pi.image_url, p.status, c.name as category_name
      FROM browse_history h
      JOIN products p ON h.product_id = p.product_id
      LEFT JOIN categories c ON p.category_id = c.category_id
      LEFT JOIN (
        SELECT product_id, image_url
        FROM product_images
        WHERE (product_id, sort_order) IN (
          SELECT product_id, MIN(sort_order)
          FROM product_images
          GROUP BY product_id
        )
      ) pi ON p.product_id = pi.product_id
      WHERE h.user_id = ?
    `;
    const params = [userId];

    // 关键词搜索
    if (keyword) {
      sql += ' AND p.title LIKE ?';
      params.push(`%${keyword}%`);
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [浏览历史] 关键词搜索: ${keyword}`);
    }

    // 分类筛选
    if (category_ids) {
      const categoryArray = category_ids.split(',').map(Number);
      sql += ` AND p.category_id IN (${categoryArray.map(() => '?').join(',')})`;
      params.push(...categoryArray);
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [浏览历史] 分类筛选: ${categoryArray}`);
    }

    // 价格范围筛选
    if (min_price) {
      sql += ' AND p.price >= ?';
      params.push(Number(min_price));
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [浏览历史] 最低价格筛选: ${min_price}`);
    }
    if (max_price) {
      sql += ' AND p.price <= ?';
      params.push(Number(max_price));
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [浏览历史] 最高价格筛选: ${max_price}`);
    }

    // 时间范围筛选
    if (time_range) {
      let timeCondition = '';
      switch (time_range) {
        case 'today':
          timeCondition = ' AND h.view_time >= CURDATE()';
          break;
        case 'week':
          timeCondition = ' AND h.view_time >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK)';
          break;
        case 'month':
          timeCondition = ' AND h.view_time >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)';
          break;
        case 'quarter':
          timeCondition = ' AND h.view_time >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)';
          break;
      }
      sql += timeCondition;
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [浏览历史] 时间范围筛选: ${time_range}`);
    }

    // 排序
    let orderBy = ' ORDER BY h.view_time DESC';
    switch (sort_by) {
      case 'view_time_asc':
        orderBy = ' ORDER BY h.view_time ASC';
        break;
      case 'price_desc':
        orderBy = ' ORDER BY p.price DESC';
        break;
      case 'price_asc':
        orderBy = ' ORDER BY p.price ASC';
        break;
    }
    sql += orderBy;

    // 分页
    sql += ' LIMIT ? OFFSET ?';
    params.push(itemsPerPage, offset);

    // 查询总数的SQL
    const countSql = `
      SELECT COUNT(DISTINCT h.history_id) as total
      FROM browse_history h
      JOIN products p ON h.product_id = p.product_id
      WHERE h.user_id = ?
      ${sql.split('WHERE h.user_id = ?')[1].split('ORDER BY')[0]}
    `;
    const countParams = [...params.slice(0, params.length - 2)]; // 移除分页参数

    // 执行查询
    const [rows] = await db.query(sql, params);
    const [countResult] = await db.query(countSql, countParams);
    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [浏览历史] 查询成功: 总数=${totalItems}, 页数=${totalPages}`);

    res.json({
      success: true,
      data: {
        products: rows,
        total_pages: totalPages,
        current_page: currentPage,
        total_items: totalItems
      }
    });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [浏览历史] 查询失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '获取浏览历史失败',
      data: {
        products: [],
        total_pages: 1,
        current_page: 1,
        total_items: 0
      }
    });
  }
};

// 获取地址列表
exports.getAddresses = async (req, res) => {
  try {
    const userId = req.user.user_id;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 请求获取地址列表`);
    const [rows] = await db.query('SELECT * FROM addresses WHERE user_id = ? ORDER BY is_default DESC, address_id DESC', [userId]);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] 用户 ${userId} 地址列表获取成功，共 ${rows.length} 条记录`);
    res.json({ success: true, addresses: rows });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 获取地址列表失败: ${error.message}`);
    res.status(500).json({ success: false, message: '获取地址列表失败', addresses: [] });
  }
};

// 添加新地址
exports.addAddress = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { recipient, phone, province, city, campus, detail_address, is_default } = req.body;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 请求添加新地址: ${JSON.stringify(req.body)}`);

    // 如果设置为默认地址，先取消其他地址的默认状态
    if (is_default) {
      await db.query('UPDATE addresses SET is_default = 0 WHERE user_id = ?', [userId]);
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] 用户 ${userId} 取消了所有地址的默认状态`);
    }

    const [result] = await db.query(
      'INSERT INTO addresses (user_id, recipient, phone, province, city, campus, detail_address, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [userId, recipient, phone, province, city, campus, detail_address, is_default ? 1 : 0]
    );

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 添加地址成功，地址ID: ${result.insertId}`);
    res.json({ success: true, message: '添加地址成功', address_id: result.insertId });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 添加地址失败: ${error.message}`);
    res.status(500).json({ success: false, message: '添加地址失败' });
  }
};

// 更新地址
exports.updateAddress = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { address_id } = req.params;
    const { recipient, phone, province, city, campus, detail_address, is_default } = req.body;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 请求更新地址 ${address_id}: ${JSON.stringify(req.body)}`);

    // 检查地址是否属于当前用户
    const [addresses] = await db.query('SELECT * FROM addresses WHERE address_id = ? AND user_id = ?', [address_id, userId]);
    if (addresses.length === 0) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] 用户 ${userId} 无权修改地址 ${address_id}`);
      return res.status(403).json({ success: false, message: '无权修改此地址' });
    }

    // 如果设置为默认地址，先取消其他地址的默认状态
    if (is_default) {
      await db.query('UPDATE addresses SET is_default = 0 WHERE user_id = ?', [userId]);
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] 用户 ${userId} 取消了所有地址的默认状态`);
    }

    await db.query(
      'UPDATE addresses SET recipient = ?, phone = ?, province = ?, city = ?, campus = ?, detail_address = ?, is_default = ? WHERE address_id = ? AND user_id = ?',
      [recipient, phone, province, city, campus, detail_address, is_default ? 1 : 0, address_id, userId]
    );

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 更新地址 ${address_id} 成功`);
    res.json({ success: true, message: '更新地址成功' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 更新地址失败: ${error.message}`);
    res.status(500).json({ success: false, message: '更新地址失败' });
  }
};

// 删除地址
exports.deleteAddress = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { address_id } = req.params;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 请求删除地址 ${address_id}`);

    // 检查地址是否属于当前用户
    const [addresses] = await db.query('SELECT * FROM addresses WHERE address_id = ? AND user_id = ?', [address_id, userId]);
    if (addresses.length === 0) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] 用户 ${userId} 无权删除地址 ${address_id}`);
      return res.status(403).json({ success: false, message: '无权删除此地址' });
    }

    await db.query('DELETE FROM addresses WHERE address_id = ? AND user_id = ?', [address_id, userId]);

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 删除地址 ${address_id} 成功`);
    res.json({ success: true, message: '删除地址成功' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 删除地址失败: ${error.message}`);
    res.status(500).json({ success: false, message: '删除地址失败' });
  }
};

// 设置默认地址
exports.setDefaultAddress = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { address_id } = req.params;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 请求设置地址 ${address_id} 为默认地址`);

    // 检查地址是否属于当前用户
    const [addresses] = await db.query('SELECT * FROM addresses WHERE address_id = ? AND user_id = ?', [address_id, userId]);
    if (addresses.length === 0) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] 用户 ${userId} 无权设置地址 ${address_id} 为默认地址`);
      return res.status(403).json({ success: false, message: '无权设置此地址为默认' });
    }

    // 取消其他地址的默认状态
    await db.query('UPDATE addresses SET is_default = 0 WHERE user_id = ?', [userId]);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] 用户 ${userId} 取消了所有地址的默认状态`);

    // 设置当前地址为默认
    await db.query('UPDATE addresses SET is_default = 1 WHERE address_id = ? AND user_id = ?', [address_id, userId]);

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 用户 ${userId} 设置地址 ${address_id} 为默认地址成功`);
    res.json({ success: true, message: '设置默认地址成功' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 设置默认地址失败: ${error.message}`);
    res.status(500).json({ success: false, message: '设置默认地址失败' });
  }
};

// 用户注册
exports.register = async (req, res) => {
  try {
    // 记录请求参数日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 接收到注册请求: ${JSON.stringify(req.body)}`);
    const { student_id, username, phone, email, password, confirm_password } = req.body;

    // 验证两次密码是否一致
    if (password !== confirm_password) {
      return res.status(400).json({ message: '两次密码输入不一致' });
    }
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] 两次密码输入一致`);
    // 检查用户是否已存在
    const [userExists] = await db.query(
      'SELECT * FROM users WHERE student_id = ? OR email = ?',
      [student_id, email]
    );
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] 查询用户存在结果: ${JSON.stringify(userExists)}`);
    if (userExists.length > 0) {
      return res.status(400).json({ message: '学号或邮箱已被注册' });
    }

    // 密码加密.
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 默认头像
    const defaultAvatar = '/uploads/avatars/default.svg';

    // 插入新用户
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] 准备插入新用户: ${JSON.stringify({ student_id, username, email, phone })}`);
    const [result] = await db.query(
      'INSERT INTO users (student_id, username, email, phone, password_hash, avatar_url,role) VALUES (?, ?, ?, ?, ?, ?,0)',
      [student_id, username, email, phone, hashedPassword, defaultAvatar]
    );

    // 记录响应结果日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 注册成功: 用户ID=${result.insertId}`);
    res.status(201).json({
      message: '注册成功',
      userId: result.insertId
    });
  } catch (error) {
    // 记录错误日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 注册失败: ${error.message}`);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 用户登录
exports.login = async (req, res) => {
  try {
    // 记录请求参数日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 接收到登录请求: ${JSON.stringify(req.body)}`);
    const { account, password } = req.body;

    // 查找用户（支持学号或邮箱登录）
    const [users] = await db.query(
      'SELECT * FROM users WHERE student_id = ? OR email = ? OR phone = ? OR user_id = ?',
      [account, account, account, account]
    );

    if (users.length === 0) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] 用户不存在: ${account}`);
      return res.status(400).json({ message: '账号或密码错误' });
    }

    const user = users[0];

    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password_hash);
    if (!isMatch) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] 密码不匹配: 用户ID=${user.user_id}`);
      return res.status(400).json({ message: '账号或密码错误' });
    }

    // 更新用户在线状态
    await db.query('UPDATE users SET login = 1 WHERE user_id = ?', [user.user_id]);

    // 生成JWT
    const token = jwt.sign(
      { id: user.user_id, username: user.username, role: user.role },
      process.env.JWT_SECRET || 'your_jwt_secret',
      { expiresIn: '24h' }
    );

    // 记录响应结果日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 登录成功: 用户ID=${user.user_id}`);
    res.json({
      token,
      user: {
        id: user.user_id,
        studentId: user.student_id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        avatar: user.avatar_url,
        role: user.role
      }
    });
  } catch (error) {
    // 记录错误日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 登录失败: ${error.message}`);
    res.status(500).json({ message: '服务器错误' });
  }
};
// 用户登出
exports.logout = async (req, res) => {
  try {
    const userId = req.user.user_id;
    // 更新用户登录状态
    await db.query('UPDATE users SET login = 0 WHERE user_id = ?', [userId]);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [登出] 用户 ${userId} 登出成功`);
    res.json({ success: true, message: '登出成功' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [登出] 登出失败: ${error.message}`);
    res.status(500).json({ success: false, message: '登出失败' });
  }
};

// 验证token有效性
exports.validateToken = async (req, res) => {
  try {
    const { token } = req.body;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [token验证] 接收到token验证请求`);
    
    if (!token) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [token验证] 未提供token`);
      return res.status(400).json({ valid: false, message: '未提供token' });
    }
    
    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your_jwt_secret');
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [token验证] token解码成功: 用户ID=${decoded.id}`);
    
    // 检查用户是否存在且登录状态有效
    const [users] = await db.query(
      'SELECT * FROM users WHERE user_id = ? AND login = 1',
      [decoded.id]
    );
    
    if (users.length === 0) {
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [token验证] 用户不存在或登录状态无效: 用户ID=${decoded.id}`);
      return res.status(401).json({ valid: false, message: '用户不存在或登录状态无效' });
    }
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [token验证] token有效: 用户ID=${decoded.id}`);
    res.json({ valid: true, message: 'token有效', user: {
      id: users[0].user_id,
      username: users[0].username,
      role: users[0].role
    } });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [token验证] 验证失败: ${error.message}`);
    res.status(401).json({ valid: false, message: 'token无效或已过期' });
  }
}
// 获取当前用户信息
exports.profile = async (req, res) => {
  try {
    // 直接返回登录用户的关键信息
    const user = req.user;
    res.json({
      user: {
        id: user.user_id,
        username: user.username,
        email: user.email,
        avatar: user.avatar_url,
        studentId: user.student_id,
        phone: user.phone
      }
    });
  } catch (error) {
    res.status(500).json({ message: '获取用户信息失败' });
  }
};



// 导出控制器
module.exports = exports;